Add Points with Buttons

Introduction

Let’s add a point to your score when a button is pressed on the micro:bit!

A graphic depicting someone pressing a button

Step 2

We ‘ll start by adding code to the ||input:on button pressed||
container already in the workspace.

💡 You can click the arrow next to ||input:A|| and change to another button if you prefer.

input.onButtonPressed(Button.A, function() { })

Step 3

Open the ||variables:Variables|| category
and drag ||variables:change [score] by [1]||
into the empty ||input:on button [A] [pressed]||.

input.onButtonPressed(Button.A, function() {
    score += 1
    })

Step 4

Update the LEDs after you change the score by opening the
||basic:Basic|| category and dragging ||basic:show number [score]||
into the end of the ||input:on button [A] [pressed]|| container already in the workspace.

pins.onPulsed(DigitalPin.P0, PulseValue.High, function () {
    score += 1
    basic.showNumber(score)
})

Step 4

Click the A button in the simulator to give your code a try.

You should see the score go up each time the button is pressed.

Step 5

Add sound effects.

Open the ||music:Music|| category and
drag ||music:play [〰️] [in background]||
into the end of the ||input:on button [A] [pressed]|| container in the workspace.

pins.onPulsed(DigitalPin.P0, PulseValue.High, function () {
    score += 1
    basic.showNumber(score)
    music._playDefaultBackground(music.createSoundExpression(WaveShape.Square, 400, 600, 255, 0, 100, SoundExpressionEffect.Warble, InterpolationCurve.Linear), music.PlaybackMode.InBackground)
})

Step 6

Test again by pressing A

Your program should play a sound and increase your points with each click.

💡 You may need to unmute the simulator to hear your music.

Step 7

If you have a micro:bit connected, click |Download| and transfer your code.

Now you’re ready to attach your micro:bit to your project and try it out!

    music._playDefaultBackground(music.createSoundExpression(WaveShape.Square, 400, 600, 255, 0, 100, SoundExpressionEffect.Warble, InterpolationCurve.Linear), music.PlaybackMode.InBackground)
    basic.showNumber(score)
input.onButtonPressed(Button.A, function() {})

let score = 0
score = 0
basic.showNumber(score)
basic.showIcon(IconNames.Yes)
    score += 1


let score = 0
basic.showNumber(score)